package com.apes.scm.masterdata.product.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.ProductUomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 功能：计量单位服务
 *
 * @author xul
 * @create 2018-06-06 10:14
 */
@Service("productUomService")
public class ProductUomService extends DomainService {

    @Autowired
    ProductUomRepository uomRepository;

    public ProductUom save(SimpleRequest request) {
        ProductUom productUom = request.getO(ProductUom.class);
        check(productUom);
        return uomRepository.saveAndFlush(productUom);
    }

    public ProductUom update(SimpleRequest request) {
        ProductUom productUom = request.getO(ProductUom.class);
        check(productUom);
        return uomRepository.saveAndFlush(productUom);
    }

    private void check(ProductUom productUom) {
        if (productUom.getFactor() < 0) throw new RuntimeException("‘比例’值不允许小于零！");
        if (productUom.getUomType().getCode().equals("reference")) {
            productUom.setFactor(1);
        } else if (productUom.getUomType().getCode().equals("bigger") && productUom.getFactor() > 1) {
            throw new RuntimeException("‘比例’值不允许大于1！");
        } else if (productUom.getUomType().getCode().equals("smaller") && productUom.getFactor() <= 1) {
            throw new RuntimeException("‘比例’值不允许小于1！");
        }
    }

    public List<ProductUom> findAllByCategory(SimpleRequest request) {
        ProductUom uom = uomRepository.findOne(Long.valueOf(request.get("id")));
        return uomRepository.findAllByUomCategory(uom.getUomCategory());
    }


    /***
     * 计量单位换算（数量）
     * @param request
     * @return
     */
    public double computeQty(SimpleRequest request) {
        JSONObject tempJson = request.getJO();
        ProductUom uom = uomRepository.findOne(tempJson.getJSONObject("uom").getLong("id"));
        ProductUom toUom = uomRepository.findOne(tempJson.getJSONObject("toUom").getLong("id"));
        return uom.computeQty(tempJson.getDouble("qty"), toUom,
                tempJson.getBoolean("round") == null ? false :
                        tempJson.getBoolean("round"));
    }

    /***
     * 计量单位换算（金额）
     * @param request
     * @return
     */
    public double computePrice(SimpleRequest request) {
        JSONObject tempJson = request.getJO();
        ProductUom uom = uomRepository.findOne(tempJson.getJSONObject("uom").getLong("id"));
        ProductUom toUom = uomRepository.findOne(tempJson.getJSONObject("toUom").getLong("id"));
        return uom.computePrice(tempJson.getDouble("price"), toUom);
    }

    public Page<ProductUom> find(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        if (filters.size() > 0) {
            filters = filters.stream().filter(filter -> {
                try {
                    if ("id".equals(filter.get("field"))) {
                        Long.valueOf(filter.get("value").toString());
                    }
                    return true;
                } catch (Exception e) {
                    return false;
                }
            }).collect(Collectors.toList());
        }

        return uomRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 根据计量单位名称、商品编码获取计量单位信息
     * @param pJLDW
     * @param pSPID
     * @return
     */
    public List<ProductUom> jldwGetProductUom(String pJLDW, String pSPID) {
        List<ProductUom> productUomList = uomRepository.findAll(JpaDsl.toCriteriaByEq("name", pJLDW, "uomCategory.id", pSPID));
        if (productUomList.size() == 0) {
            throw new RuntimeException("未找到对应计量单位：" + pJLDW + ", 类别：" + pSPID);
        }
        return productUomList;
    }
}
